﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Web;

namespace Classified.Web.Helpers
{
    public class EmailHelper
    {
        public static bool SendEmail(string fromEmail, string toEmail, string subject, string body, string from)
        {
            MailMessage message = new MailMessage();
            SmtpDetails objSmtpDetails = new SmtpDetails();
            objSmtpDetails = GetSmtpDetails();
            try
            {
                MailAddress fromAddress = new MailAddress(fromEmail, from);
                message.From = fromAddress;
                message.To.Add(toEmail);
                message.Subject = subject;
                message.IsBodyHtml = true;
                message.Body = body;
                // Send SMTP mail
                SmtpClient smtp = new SmtpClient(objSmtpDetails.SmtpServer);
                smtp.Credentials = new System.Net.NetworkCredential(objSmtpDetails.UserName, objSmtpDetails.Password);
                smtp.Port = objSmtpDetails.PortNO;
                smtp.EnableSsl = objSmtpDetails.EnableSsl;

                smtp.Send(message);
                return true;
            }
            catch (Exception ex)
            {
                //log error
                return false;
            }
        }

        public class SmtpDetails
        {
            public bool EnableSsl { get; set; }
            public int PortNO { get; set; }
            public string SmtpServer { get; set; }
            public string UserName { get; set; }
            public string Password { get; set; }
        }


        private static SmtpDetails GetSmtpDetails()
        {
            AppSettingsReader objAppSettingsReader = new AppSettingsReader();
            SmtpDetails objSmtpDetails = new SmtpDetails();
            objSmtpDetails.EnableSsl = Convert.ToBoolean(objAppSettingsReader.GetValue("EnableSsl", typeof(string)));
            objSmtpDetails.UserName = objAppSettingsReader.GetValue("Adsx24NotificationEmail", typeof(string)).ToString();
            objSmtpDetails.Password = objAppSettingsReader.GetValue("Adsx24NotificationPassword", typeof(string)).ToString();
            objSmtpDetails.PortNO = Convert.ToInt32(objAppSettingsReader.GetValue("SmtpPort", typeof(string)));
            objSmtpDetails.SmtpServer = objAppSettingsReader.GetValue("SmtpServer", typeof(string)).ToString();
            return objSmtpDetails;
        }
    }
}